<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
	<title>Local Wallet</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=8"/>
	<link type="text/css" rel="stylesheet" href="css/reset.css" />
	<link type="text/css" rel="stylesheet" href="css/main.css" />
	<link type="text/css" rel="stylesheet" href="css/jquery-ui/hot-sneaks/jquery-ui-1.8.11.custom.css" />
	<link type="text/css" rel="stylesheet" href="css/jquery-ui-override.css" />
	<script type="text/javascript" src="script/jquery-1.5.1.min.js"></script>
	<script type="text/javascript" src="script/jstorage.js"></script>
	<script type="text/javascript" src="script/jquery-jtemplates.js"></script>
	<script type="text/javascript" src="script/jquery.custom.selectors.js"></script>
	<script type="text/javascript" src="script/jquery.quicksearch.js"></script>
</head>
<body>
<div id="wrapper">
	<div id="wrap">
		<div id="container" class="ui-tabs ui-widget ui-widget-content ui-corner-all">
			<ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all">
				<li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active">
					<a href="javascript:void()"><span>Home</span></a>
				</li>
				<li class="ui-state-default ui-corner-top">
					<a href="statistics.html"><span>Statistics</span></a>
				</li>
				<input id="search" type="text" placeholder="search"/>
				<button title="Export data" id="exportButton" class="lw-btn export-btn toolbar-btns"><span>Export</span></button>
				<button title="Import data" id="importButton" class="lw-btn import-btn toolbar-btns"><span>Import</span></button>
			</ul>
			<div id="tab1" class="clearfix ui-tabs-panel ui-widget-content ui-corner-bottom">
				<div id="controls">
					<!-- controls goes here -->
				</div>
				<div id="recordsPlaceHolder">
					<!-- records goes here -->
				</div>
			</div> <!-- End Tab1 -->
		</div> <!-- End Container -->
	</div> <!-- End Wrap -->
</div> <!-- End Wrapper -->
<div id="deleteDialog" title="Delete" style="display:none;">
	<p><strong></strong> Will be deleted, Are you ?</p>
</div> <!-- End Delete Dialog -->
<div id="exportDialog" class="data-dialog" title="Export Data" style="display:none">
	<label for="fileName">File Name:</label>
	<input id="fileName" type="text" value="" />
	<p>Copy the following text into a separate file and save it for backup:</p>
	<textarea rows="5" cols="44" id="exportArea"></textarea>
</div>
<div id="importDialog" class="data-dialog" title="Import Data" style="display:none">
	<p>Paste your backed up data into the following field to retrieve them:</p>
	<textarea rows="5" cols="44" id="importArea"></textarea>
</div>
<script type="text/javascript" src="script/dao.commons.js"></script>
<script type="text/javascript" src="script/json.commons.js"></script>
<script type="text/javascript" src="script/jquery-ui-1.8.11.custom.min.js"></script>
<script type="text/javascript" src="script/jquery-ui.combo-box.js"></script>
<!--script type="text/javascript" src="script/common.behaviour.js"></script-->
<script type="text/javascript" src="script/common.behaviour.js"></script>
<script type="text/javascript">
$(document).ready(function(){
			
	/*
	 * Tracer code
	 */
	var Tracer = function() {};
	Tracer.prototype.index = 0;
	Tracer.prototype.trace = function() {
	    this.index++;
	    console.log('trace ' + this.index);
	}
	var t = new Tracer();
	
	$.lwData = getData() || $.lwData;
	
	$.prototype.categories = commons.categories;
	
	var format = "dd-mm-yy";
	//$("#controls .date-field").datepicker({ dateFormat: "dd-mm-yy" });
	
	$('body').delegate('.date-field', 'focus', function(){
		$(this).datepicker({dateFormat: format});
	});
	
	if($.lwData) {
		var inner = $.createTemplateURL('template/tmpl-controls.html');
		$('#recordsPlaceHolder').setTemplateURL('template/tmpl-records.html', {inn: inner});
		$('#controls').setTemplate(inner);
		$('#controls').processTemplate();
		$('#recordsPlaceHolder').processTemplate($.lwData);
		$('#controls .hot-select').eq(0).combobox();
	}
	
	// quick search
	//setTimeout(function(){
			$('#search').quicksearch('#recordsPlaceHolder .record-element', {
				selector: '.lw-desc'
			});
	//	}, 500
	//);
	
	// add button
	$('#addButton').click(function(){
		var max = getNextID();
		var newRecord =  {
			category	:	$('#controls .hot-select').val(),
			description	:	$('#controls .desc-field').val(),
			amount		:	parseFloat($('#controls .amount-field').val()),
			date		:	(getDate($('#controls .date-field').val()))
		}
		$.lwData.records[max] = newRecord;
		$('#controls .hot-field').not('.date-field').val('');
		//$('#controls .inplace-select').focus();
		$('#controls .ui-autocomplete-input').focus().select();
		storeData($.lwData);
		setNextID(max);
		$('#recordsPlaceHolder').processTemplate($.lwData);
	});
	
	// edit button
	$('body').delegate('.edit-btn', 'click', function(){
		var $this = $(this).closest('.record-element');
		// if edit mode
		if(!$this.hasClass('edit')) {
			$this.addClass('edit');
			$('#editControls').children().clone().show().appendTo($this.children('.record-edit'));
			$this.fillInPlace({
				data: getRecordValues($this)
			});
			$this.find('.record-edit .date-field').datepicker({ dateFormat: "dd-mm-yy" }).show();
		// done edit
		} else {
			$this.removeClass('edit');
		}
	});
	
	(function($){
		// extending jquery object
		$.extend({
			
		});
		// extending jquery function
	 	$.fn.extend({ 
	 		fillInPlace: function(options) {
				var defaults = {
					data: {
						category: '',
						date: (new Date().getTime()),
						description: '',
						amount: ''
					}
				}
				var options =  $.extend(defaults, options);
	    		return this.each(function() {
					var $elem = $(this).find('.record-edit');
					$elem.children('select').val(options.data.category);
					$elem.children('.date-field').val(transformTime(options.data.date));
					$elem.children('.desc-field').val(options.data.description);
					$elem.children('.amount-field').val(options.data.amount);
	    		});
	    	},
			updateValues: function(obj) {
				return this.each(function(){
					var $record = $(this);
					var $display = $record.children('.record-display');
					var img = 'images/icons/'+getCategoryIcon(obj.category);
					var title = getCategoryName(obj.category);
					$display.children('.lw-category').val(obj.category);
					$display.children('img')
						.attr('src', img)
						.attr('title', title)
						.attr('alt', title);
					date: $display.children('.lw-date').val(transformTime(obj.date));
					description: $display.children('.lw-desc').text(obj.description);
					amount: $display.children('.lw-amount').text(obj.amount);
				});
			},
			// object must be '.record-element'
			// does not return jQuery object
			getValues: function() {
				var $record = $(this)
				var $display = $record.children('.record-display');
				var temp = {};
				temp/*[$record.attr('data-id')]*/ = {
					category: $display.children('.lw-category').attr('data-value'),
					date: $display.children('.lw-date').attr('data-time'),
					description: $display.children('.lw-desc').text(),
					amount: $display.children('.lw-amount').text()
				}
				return temp;
				/*{
					id: $record.attr('data-id'),
					
				};*/
			},
			getEditValues: function() {
				var $record = $(this)
				var $display = $record.children('.record-edit');
				var temp = {};
				temp/*[$record.attr('data-id')]*/ = {
					category: $display.children('.inplace-select').val(),
					date: (getDate($display.children('.date-field').val())),
					description: $display.children('.desc-field').val(),
					amount: $display.children('.amount-field').val()
				}
				return temp;
			}
		});
	})(jQuery);
	
	function getRecordValues($record) {
		var $display = $record.children('.record-display');
		return {
			id: $record.attr('data-id'),
			category: $display.children('.lw-category').attr('data-value'),
			date: $display.children('.lw-date').attr('data-time'),
			description: $display.children('.lw-desc').text(),
			amount: $display.children('.lw-amount').text()
		};
	}
	
	// cancel button
	$('body').delegate('.cancel-btn', 'click', function(){
		removeEdit($(this))
	});
	
	function removeEdit($record) {
		$record.closest('.record-edit').html('').parent().removeClass('edit');
	}
	
	// save button
	$('body').delegate('.save-btn', 'click', function(){
		var $record = $(this).closest('.record-element');
		var id = $record.attr('data-id');
		var obj = $record.getEditValues();
		$.lwData.records[id] = obj;
		//var obj = getRecordValues($record);
		//if(updateData(obj)) {
			storeData($.lwData);
			$record.updateValues(obj);
			removeEdit($(this))
		//}
	});
	
	// delete button
	$('body').delegate('.delete-btn', 'click', function(){
		var $record = $(this).closest('.record-element');
		var obj = $record.getValues();
		var id = $record.attr('data-id');
		$('#deleteDialog').dialog({
			resizable: false,
			open: function() {
				$(this).find('strong').html(obj.description);
			},
			buttons: {
				'Delete' : function() {
					delete $.lwData.records[id];
					storeData($.lwData);
					$record.slideUp($.lwData.speed, function(){
						$(this).remove();
					});
					$(this).dialog('close');
				},
				Cancel : function() {
					$(this).dialog('close');
				}
			}
		});
	});
	
	// export data
	$('#exportButton').click(function(){
		$('#exportDialog').dialog({
			resizable: false,
			modal: true,
			open: function() {
				var $area = $(this).find('textarea');
				$('#fileName').val(generateFileName());
				$area.val(JSON.stringify(getData()));
				$area.get(0).focus();
				$area.get(0).select();
			},
			buttons: {
				'Select All': function() {
					var $area = $(this).find('textarea');
					$area.get(0).focus();
					$area.get(0).select();
				},
				'Close': function() {
					$(this).dialog('close');
				}
			}
		});
	});
	
	function generateFileName() {
		//lw-09-04-2011-0232.txt
		var str = 'lw-';
		var date = new Date();
		str += leadingZero(date.getDate()) + '-' 
				+ leadingZero(date.getMonth()+1) + '-' 
				+ date.getFullYear() + '-' 
				+ leadingZero(date.getHours()) 
				+ leadingZero(date.getMinutes()) 
				+ leadingZero(date.getSeconds()) + '.txt';
		return str;
	}
	
	function leadingZero(num) {
		return (num < 10 ? ('0'+num) : ''+num);
	}
			
}); // end of document ready
</script>
</body>
</html>